<template>
  <view class="container">
    <view class="logo-section">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="app-name">家电商城</text>
    </view>

    <!-- <view class="form-section">
      <uni-forms ref="form" :model="formData" :rules="rules">
        <uni-forms-item name="username">
          <uni-easyinput
            v-model="formData.username"
            placeholder="请输入用户名"
            :clearable="true"
            :prefixIcon="'person'"
          />
        </uni-forms-item>

        <uni-forms-item name="password">
          <uni-easyinput
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            :clearable="true"
            :prefixIcon="'locked'"
          />
        </uni-forms-item>
      </uni-forms>

      <button class="login-btn" @click="login">登录</button>
    </view> -->

    <!-- 手机号快捷登录 -->
    <view class="wechat-login-section">
      <!-- 简化的微信登录按钮 -->
      <!-- <button
        class="wechat-login-btn"
        open-type="getUserInfo"
        @getuserinfo="getuserinfo"
        withCredentials="true"
        :disabled="wechatLogging"
      >
        <image class="wechat-icon" src="/static/icons/wechat.png" mode="aspectFit" />
        <text class="wechat-text">{{ wechatLogging ? '登录中...' : '手机号快捷登录' }}</text>
      </button> -->
      <!-- 普通按钮：先检查协议 -->
      <button v-if="!isAgreed" class="wechat-login-btn" @click="checkAgreement">
        <text class="wechat-text">手机号快捷登录</text>
      </button>

      <!-- 授权按钮：勾选协议后显示 -->
      <button
        v-else
        class="wechat-login-btn"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber"
        withCredentials="true"
        :disabled="wechatLogging"
      >
        <text class="wechat-text">
          {{ wechatLogging ? '登录中...' : '手机号快捷登录' }}
        </text>
      </button>
      <button
        v-if="env === 'develop' || env === 'trial'"
        class="wechat-login-btn"
        withCredentials="true"
        :disabled="wechatLogging"
        @click="auditQuickLogin"
      >
        <text class="wechat-text">
          审核快捷登录
        </text>
      </button>

      <!-- 返回按钮 -->
      <button class="back-btn" @click="goBack">
        <text class="back-text">暂不登录，返回个人中心</text>
      </button>
    </view>

    <!-- 快速登录（仅用于测试） -->
    <!-- <view class="quick-login">
      <text class="quick-title">快速登录（测试用）</text>
      <view class="quick-buttons">
        <button class="quick-btn normal" @click="quickLogin('normal')">普通用户</button>
        <button class="quick-btn sales" @click="quickLogin('sales')">销售人员</button>
      </view>
    </view> -->

    <!-- 注册链接 -->
    <!-- <view class="register-link">
      <text>还没有账号？</text>
      <text class="link" @click="goToRegister">立即注册</text>
    </view> -->

    <!-- 用户协议 -->
    <view class="agreement">
      <checkbox-group @change="onAgreementChange">
        <label class="agreement-label">
          <checkbox :checked="isAgreed" color="#1aad19" />
          <text class="agreement-text">我已阅读并同意</text>
          <text class="link" @click.stop="openUserAgreement">《用户协议》</text>
          <text class="agreement-text">和</text>
          <text class="link" @click.stop="openPrivacyPolicy">《隐私政策》</text>
        </label>
      </checkbox-group>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onUnload } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { isLoggedIn, setAuthInfo } from '@/utils/auth';

const wechatLogging = ref(false);
const referralCode = ref('');
const isAgreed = ref(false);



// // 表单数据
// const formData = reactive({
//   username: '',
//   password: '',
// });

// // 表单验证规则
// const rules = {
//   username: {
//     rules: [
//       { required: true, errorMessage: '请输入用户名' },
//       {
//         minLength: 3,
//         maxLength: 20,
//         errorMessage: '用户名长度在3-20个字符之间',
//       },
//     ],
//   },
//   password: {
//     rules: [
//       { required: true, errorMessage: '请输入密码' },
//       { minLength: 6, maxLength: 20, errorMessage: '密码长度在6-20个字符之间' },
//     ],
//   },
// };

// // 微信获取用户信息并打印
// const getuserinfo = () => {
//   uni.login({
//     success: (res: any) => {
//       if (res.code) {
//         console.log('成功', res);

//         //获取token
//         uni.request({
//           url: 'https://api.weixin.qq.com/cgi-bin/token',
//           success: (res_token: any) => {
//             console.log(res_token);
//           },
//         });

//         // 获取手机号
//         // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

//         // uni.request({
//         //   url: 'https://api.weixin.qq.com/sns/jscode2session',
//         //   data: {
//         //     appid: 'wx3857e85d91d69098',
//         //     secret: '84d063cc22d3b7cbda2f258960726b97',
//         //     js_code: res.code,
//         //     grant_type: 'authorization_code',
//         //   },
//         //   success: (res: any) => {
//         //     console.log(res);
//         //   },
//         // });
//       }
//       // 这里可以将code发送到后端获取openid和session_key
//     },
//     fail: (err: any) => {
//       console.log('登录失败:', err);
//     },
//   });
// };

// 复选框变化事件
const onAgreementChange = (e: any) => {
  isAgreed.value = e.detail.value.length > 0;
};

// 打开用户协议
const openUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/user/user-agreement',
  });
};

// 打开隐私政策
const openPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/user/privacy-policy',
  });
};

// 检查是否勾选协议
const checkAgreement = () => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议和隐私政策',
      icon: 'none',
      duration: 2000,
    });
  }
};

// 获取手机号
const getPhoneNumber = (e: any) => {
  console.log('getPhoneNumber event:', e.detail);

  // 用户点击了取消按钮，不显示任何提示，允许用户自由选择
  if (!e.detail.code) {
    console.log('用户取消授权');
    // 不显示任何错误提示，尊重用户选择
    return;
  }

  // 用户同意授权，开始登录流程
  wechatLogging.value = true;

  uni.login({
    success: async (res: any) => {
      if (res.code) {
        const requestData: any = {
          clientId: 'be7052a7e4f802c20df10a8d131adb12',
          grantType: 'xcx',
          code: res.code,
          phoneCode: e.detail.code,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData,
        };

        // 如果有推广码（用户ID），添加到请求数据中
        if (referralCode.value) {
          requestData.referralCode = referralCode.value;
          console.log('包含推广码（用户ID）:', referralCode.value);
        } else {
          console.log('无推广码，直接获取手机号');
        }

        // 调用登录接口
        uni.showLoading({
          title: '登录中...',
        });

        console.log(requestData);

        try {
          const response = await request({
            url: '/auth/login',
            method: 'POST',
            data: requestData,
          });

          console.log('response', response);

          // 获取用户类型，默认为普通用户
          const userType = response.data?.salesFlag || 'normal';

          // 构建用户信息
          const userInfo = {
            id: response.data?.openid || Date.now(),
            username: response.data?.userName || '微信用户',
            nickname: response.data?.userName || '微信用户',
            userType: userType, // normal: 普通用户, sales: 销售人员
            phone: '',
            avatar: '/static/avatar.png',
            openid: response.data?.openid,
          };

          // 使用新的认证信息设置方法
          if (response.data && response.data.access_token) {
            setAuthInfo(
              response.data.access_token,
              userInfo,
              response.data.refresh_token
            );
          }

          // 先隐藏 loading，再显示成功提示
          uni.hideLoading();

          uni.showToast({
            title: '登录成功',
            icon: 'success',
          });

          // 跳转到个人中心
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index',
            });
          }, 1500);
        } catch (error) {
          console.error('登录失败:', error);
          // 确保在错误情况下也隐藏 loading
          uni.hideLoading();
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none',
          });
        } finally {
          wechatLogging.value = false;
        }
      } else {
        // uni.login 失败的情况
        wechatLogging.value = false;
        uni.showToast({
          title: '微信登录失败',
          icon: 'none',
        });
      }
    },
    fail: (err: any) => {
      console.error('uni.login 失败:', err);
      wechatLogging.value = false;
      uni.showToast({
        title: '微信登录失败',
        icon: 'none',
      });
    },
  });
};

// 返回首页
const goBack = () => {
  uni.switchTab({
    url: '/pages/user/profile',
  });
};

// 快速登录（测试用）
const quickLogin = (userType: string) => {
  uni.showLoading({
    title: '登录中...',
  });

  setTimeout(() => {
    // 构建用户信息
    const userInfo = {
      id: 1,
      username: userType === 'sales' ? 'sales001' : 'user001',
      nickname: userType === 'sales' ? '销售人员' : '普通用户',
      avatar: '/static/avatar.png',
      userType: userType as 'normal' | 'sales', // normal: 普通用户, sales: 销售人员
      phone: '',
    };

    // 使用新的认证信息设置方法
    setAuthInfo('mock_token_' + Date.now(), userInfo);

    uni.hideLoading();
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    });

    // 跳转到个人中心
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/user/profile',
      });
    }, 1500);
  }, 1000);
};

// 跳转到注册页面（暂时注释，如需要可取消注释）
// const goToRegister = () => {
//   uni.navigateTo({
//     url: '/pages/user/register',
//   });
// };

// 页面加载时检查推广码和登录状态
onMounted(() => {
  // 检查是否已经登录，如果已登录则跳转到个人中心
  if (isLoggedIn()) {
    uni.showToast({
      title: '您已登录',
      icon: 'success',
    });
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/user/profile',
      });
    }, 1500);
    return;
  }

  // 获取页面参数中的推广码
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage.options;

  // 检查URL参数中的referralCode
  if (options && options.referralCode) {
    referralCode.value = options.referralCode;
    console.log('检测到推广码:', referralCode.value);
    uni.showToast({
      title: '检测到推广邀请',
      icon: 'success',
    });
  }
  // 检查scene参数（小程序码扫码进入）
  else if (options && options.scene) {
    try {
      // 解析scene参数，格式为 referral=userId
      const sceneParams = decodeURIComponent(options.scene);
      const referralMatch = sceneParams.match(/referral=([^&]+)/);
      if (referralMatch) {
        referralCode.value = referralMatch[1];
        console.log('检测到小程序码推广码:', referralCode.value);
        uni.showToast({
          title: '检测到推广邀请',
          icon: 'success',
        });
      }
    } catch (error) {
      console.error('解析scene参数失败:', error);
    }
  }

  console.log('当前推广码状态:', referralCode.value || '无');
});

// 页面卸载时清空推广码
onUnload(() => {
  referralCode.value = '';
  // console.log('页面离开，推广码已清空');
});


// -----------------------------------
declare const wx: any;
let detectedEnv = 'release';
try {
  if (typeof wx !== 'undefined' && wx.getAccountInfoSync) {
    const accountInfo = wx.getAccountInfoSync();
    detectedEnv = accountInfo?.miniProgram?.envVersion || 'release';
  }
} catch (e) {}
const env = detectedEnv;
console.log('当前环境:', env);
// 'develop' 开发版
// 'trial' 体验版
// 'release' 正式版
// 审核快捷登录（开发版/体验版专用，固定参数）
const auditQuickLogin = async () => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议和隐私政策',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  wechatLogging.value = true;
  const requestData = {
    code: '0a1UFr1w3V2CB53Bn12w3tfmVC3UFr1Z',
    clientId: 'be7052a7e4f802c20df10a8d131adb12',
    grantType: 'xcx',
    encryptedData:
      'UBkFm4HkR26m/HLsNaGBkbQzG73VRqcKqBfUaz2EzZRJD1KjvhCoJuHLKaSvl9Kk3uDEAcjI8eSh48PqizIQUF/tgTtm+87cK8wuwJsmAmn0Wgxl7DydurjGA4X6XZf6Q7yqcmYZnzMgXNRzYuIOoEKBqrlsMFej6trYF+AeIO+maAzvN073rnwxdg+xV9TRqxfatQ4ktMlkbDFmqAdbWg==',
    iv: 'Nvb7hFrAE7QpvvTwnFSiUQ=='
  };

  uni.showLoading({ title: '登录中...' });
  try {
    const response = await request({
      url: '/auth/login',
      method: 'POST',
      data: requestData
    });

    const userType = response.data?.salesFlag || 'normal';
    const userInfo = {
      id: response.data?.openid || Date.now(),
      username: response.data?.userName || '微信用户',
      nickname: response.data?.userName || '微信用户',
      userType: userType,
      phone: '',
      avatar: '/static/avatar.png',
      openid: response.data?.openid
    };

    if (response.data && response.data.access_token) {
      setAuthInfo(
        response.data.access_token,
        userInfo,
        response.data.refresh_token
      );
    }

    uni.hideLoading();
    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' });
    }, 1500);
  } catch (error) {
    console.error('审核快捷登录失败:', error);
    uni.hideLoading();
    uni.showToast({ title: '登录失败，请重试', icon: 'none' });
  } finally {
    wechatLogging.value = false;
  }
};
// -----------------------------------
</script>

<style scoped>
.container {
  padding: 60rpx 40rpx;
  background-color: #fff;
  min-height: 100vh;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.app-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  margin-bottom: 40rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 40rpx;
}

/* 微信登录样式 */
.wechat-login-section {
  margin: 40rpx 0;
  text-align: center;
}

.wechat-login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #1aad19;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.wechat-icon {
  width: 40rpx;
  height: 40rpx;
}

.wechat-text {
  font-size: 32rpx;
}

.back-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: transparent;
  color: #666;
  font-size: 28rpx;
  border-radius: 44rpx;
  border: 2rpx solid #e0e0e0;
  margin-top: 20rpx;
}

.back-btn::after {
  border: none;
}

.back-text {
  font-size: 28rpx;
  color: #666;
}

.quick-login {
  margin-bottom: 40rpx;
  padding: 30rpx;
  background-color: #f8f9fa;
  border-radius: 20rpx;
}

.quick-title {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  display: block;
  margin-bottom: 20rpx;
}

.quick-buttons {
  display: flex;
  gap: 20rpx;
}

.quick-btn {
  flex: 1;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 24rpx;
  border-radius: 30rpx;
  border: none;
}

.quick-btn.normal {
  background-color: #28a745;
  color: #fff;
}

.quick-btn.sales {
  background-color: #ff6b35;
  color: #fff;
}

.register-link {
  text-align: center;
  margin-bottom: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.link {
  color: #007aff;
  margin-left: 10rpx;
}

.agreement {
  padding: 0 20rpx;
  font-size: 24rpx;
  color: #999;
  line-height: 1.8;
}

.agreement-label {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.agreement-text {
  font-size: 24rpx;
  color: #999;
  margin: 0 4rpx;
}

.agreement .link {
  color: #007aff;
  margin: 0 4rpx;
}
</style>
